package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.IdCardUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
//@Transactional

public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper,ApUserRealname> implements ApUserRealnameService {

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //校验参数（dto，分页）
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //封装查询条件
        //分页条件
        IPage<ApUserRealname> pageReq = new Page(dto.getPage(),dto.getSize());
        //状态条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        queryWrapper.eq(dto.getStatus() != null,ApUserRealname::getStatus,dto.getStatus());
        queryWrapper.orderByDesc(ApUserRealname::getCreatedTime);//按照创建时间降序排序
        //执行查询
        IPage<ApUserRealname> pageResult = page(pageReq,queryWrapper);
        //封装分页返回数据
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        responseResult.setData(pageResult.getRecords());
        return responseResult;
    }

    @Autowired
    ApUserMapper apUserMapper;

    /**
     *
     * @param dto id
     * @param status 2:审核失败，9：审核成功
     * @return
     */

    @GlobalTransactional(timeoutMills = 60000,rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //检查参数（dto   中的认证id）
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名认证信息id参数错误");
        }
        //查询实名认证信息
        ApUserRealname userRealname = getById(dto.getId());
        if (userRealname == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
        }
        //判断当前实名认证的状态（status= 1）
        if (userRealname.getStatus().intValue() !=1) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"审核状态错误");
        }
        //查询相关联的ap_user
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的APP用户不存在");
        }
        //修改实名认证的状态
        userRealname.setUpdatedTime(new Date());
        userRealname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);//修改实名认证状态
        if (status.intValue() == 2) {
            return ResponseResult.okResult();
        }
        //检验姓名和身份证是否真实
        Map map = IdCardUtil.checkIdCard(userRealname.getIdno(), userRealname.getName());
        Boolean success = (Boolean) map.get("success");
        if (!success) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"身份校验失败"+map.get("message"));
        }
        //如果状态为9
        //开通自媒体账户
        WmUser wmUser = creatWmUser(apUser);
        //创建作者信息
        creatAuthor(apUser,wmUser);
        return ResponseResult.okResult();
    }

    @Autowired
    ArticleFeign articleFeign;
    /**
     * 创建作者信息
     * @param apUser
     * @param wmUser
     */
    private void creatAuthor(ApUser apUser, WmUser wmUser) {
        ResponseResult<ApAuthor> findResult = articleFeign.findByUserId(apUser.getId());
        if (findResult.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
        ApAuthor author = findResult.getData();
        if (author == null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的作者信息已经存在");
        }
        author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        ResponseResult saveResult = articleFeign.save(author);
        if (findResult.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
    }

    @Autowired
    WemediaFeign wemediaFeign;
    /**
     * 创建自媒体账户
     * @param apUser
     * @return
     */
    private WmUser creatWmUser(ApUser apUser) {
        //使用feign根据用户名称查询自媒体账户是否存在
        ResponseResult<WmUser> findResult = wemediaFeign.findByName(apUser.getName());
        if (findResult.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
        WmUser wmUser = findResult.getData();
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的自媒体账户已经存在");
        }
        //如果不存在 ，创建自媒体账户
        wmUser  = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setScore(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (findResult.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
        return saveResult.getData();//获取带有wmUserId的自媒体账户信息
    }
}






















